<?php

namespace app\paper\service;

use think\admin\Service;
use think\facade\Cache;
use app\paper\controller\PaperTest;
use WeMini\Newtmpl;
use think\admin\Controller;
use think\facade\View;
use think\admin\service\QueueService;

/**
 * 文件解析
 * Class UserService
 * @package app\store\service
 */
class PaperTestService extends Service
{
    //检测总流程控制方法
    public function analysisFile($path,$integral_cat,$uid,$orderacc,$title,$author,$up_ip,$id = 0){
        $content = "";
        $code=0;
        if($id==0){
            $userinfo =$this->app->db->name('system_user')->where(['id'=>$uid])->find();
            if($userinfo['authorize']){
                $integral=$this->app->db->name('digit_surplus')->lock(true)->where(['uid'=>$uid,'icat_id'=>$integral_cat])->value('num');
                if($integral<1){
                    return ['code'=>0,'content'=>"积分不足"];
                }
            }

        }

        //解析文件
        $fa=$this->fileAnalysis($path);
        if($fa['code']==0){
            if($id){
                $this->app->db->name("digit_detectionlist")->where(['id'=>$id])->update(['iscode'=>-2]);
            }else{
                $id=$this->saveDetectionlist($orderacc,$title,$author,0,"",-2,$path,$uid,$integral_cat,$up_ip);
            }
            return ['code'=>0,'content'=>$fa['content']];
        }
        $fa['content']=str_replace("*", "", $fa['content']);
        $fa['content']=str_replace("<", "＜", $fa['content']);
        // 计算字数
        preg_match_all("/./us", $fa['content'], $match);
        $max_font=$this->app->db->name('digit_integral_cat')->where(['id'=>$integral_cat])->value('max_font');
        $textnumber =count($match[0]);
        if($textnumber>$max_font){
            return ['code'=>0,'content'=>"字符数超过{$max_font}字符"];
        }
        if($id){
            $this->app->db->name("digit_detectionlist")->where(['id'=>$id])->update(['iscode'=>-1]);
        }else{
            //创建订单信息
            $id=$this->saveDetectionlist($orderacc,$title,$author,$textnumber,"",-1,$path,$uid,$integral_cat,$up_ip,$fa['content']);
        }
        $queue=$this->app->db->name('system_queue')->where(['exec_desc'=>'','command'=>'xadmin:test','cat_id'=>$integral_cat,'status'=>1])->find();
        if($queue){
            $name = json_decode($queue['exec_data'],true);
            $this->app->db->name("digit_detectionlist")->where(['id'=>$id])->update(['check_ip'=>$name['ip']]);
            $redis=Cache::store('redis')->handler();
            $redis->lpush($name['code'], $id);
            $this->app->log->error("订单:".$id."任务:".$queue['code']);
        }else{
            $queue=$this->app->db->name('system_queue')->where(['command'=>'xadmin:test','cat_id'=>$integral_cat,'status'=>1])->find();
            $name = json_decode($queue['exec_data'],true);
            $this->app->db->name("digit_detectionlist")->where(['id'=>$id])->update(['check_ip'=>$name['ip']]);
            $redis=Cache::store('redis')->handler();
            $redis->lpush($name['code'], $id);
            $this->app->log->error("订单:".$id."任务:".$queue['code']);
        }
        return ['code'=>1,'content'=>"提交检测成功,请稍后查询检测报告"];
    }
    public function uptest($id,$title,$author,$content,$ip){
         //$delist=$this->app->db->name('digit_detectionlist')->where(['id'=>$id])->find();
         
           $result=$this->paperFile($title,$author,$content,$ip);
            $updata=[];
            if($result){
                if($result['result']==0){
                    $updata['iscode']=5;
                    $updata['remak']=$result['returnval'];
                    $updata['report_date']=time();
                    $this->app->db->name("digit_detectionlist")->where(['id'=>$id])->update($updata);
                    //$this->app->db->name("digit_detectionlist")->where(['id'=>$id])->update(['iscode'=>5]);
                    return ['code'=>0,'content'=>$result['returnval']];
                }else{
                   $updata['iscode']=0;
                   $updata['taskid']=$result['returnval'];
                   $updata['report_date']=time();
                    $this->app->db->name("digit_detectionlist")->where(['id'=>$id])->update($updata);
                    return ['code'=>1,'content'=>$result['returnval']];
                }
            }else{
                return ['code'=>0,'content'=>"失败"];
            }
           
            /*
        try {
           $result=$this->paperFile($title,$author,$content);
            $updata=[];
            if($result['result']==0){
                $updata['iscode']=5;
                $updata['remak']=$result['returnval'];
                $updata['report_date']=time();
                $this->app->db->name("digit_detectionlist")->where(['id'=>$id])->update($updata);
                //$this->app->db->name("digit_detectionlist")->where(['id'=>$id])->update(['iscode'=>5]);
                return ['code'=>0,'content'=>$result['returnval']];
            }else{
               $updata['iscode']=0;
               $updata['taskid']=$result['returnval'];
               $updata['report_date']=time();
                $this->app->db->name("digit_detectionlist")->where(['id'=>$id])->update($updata);
                return ['code'=>1];
            }
            
            
        }catch (\Exception $e) {
            return ['code'=>0,'content'=>"提交检测失败"];
        }
        */
    }
    
    
    //文件解析
    public function fileAnalysis($path){
        $content = "";
        $code=0;
        $type = substr($path,strpos($path, '.')+1);
        if(!file_exists($path)){
            return ['code'=>0,'content'=>"未找到文件"];
        }
        if($type=="docx"){
            //$content= $this->r($path);
            //dump($content);exit;
             try {
                $url="http://47.244.144.152/sys/api/readWordByPath?path=$path";
                $data=$this->curl_get($url);
                if($data){
                    $data = json_decode($data,true);
                    if(isset($data['data'])&&$data['data']!="文件不存在"){
                        $content = $data['data'];
                    }
                }
                if($content){
                    $code=1;
                }
            }catch (\Exception $e) {
                // 这是进行异常捕获
                $this->app->log->error("解析doc文件异常");
                $this->app->log->error($e->getMessage());
                return  ['code'=>0,'content'=>"文件解析失败"];
            }


        }elseif($type=="pdf"){
            try {
                $parser = new \Smalot\PdfParser\Parser();
                $pdf = $parser->parseFile($path);
                $pages = $pdf->getPages();
                $content="";
                foreach ($pages as $page) {
                    $content.= $page->getText(); //输出每一页的内容
                }
                //$content = $pdf->getText(); //将所有内容读取到一个字符串中
                if($content){
                    $code=1;
                }
            }catch (\Exception $e) {
                // 这是进行异常捕获
                $this->app->log->error("解析pdf文件异常");
                $this->app->log->error($e->getMessage());
                return  ['code'=>0,'content'=>"文件解析失败"];
            }

        }elseif ($type=="doc"){

            try {
                $url="http://47.244.144.152/sys/api/readWordByPath?path=$path";
                $data=$this->curl_get($url);
                if($data){
                    $data = json_decode($data,true);
                    if(isset($data['data'])&&$data['data']!="文件不存在"){
                        $content = $data['data'];
                    }
                }
                if($content){
                    $code=1;
                }
            }catch (\Exception $e) {
                // 这是进行异常捕获
                $this->app->log->error("解析doc文件异常");
                $this->app->log->error($e->getMessage());
                return  ['code'=>0,'content'=>"文件解析失败"];
            }

        }elseif($type=="txt"){
            try {
                $handle = fopen($path, 'r');
                while(!feof($handle)){
                    $content .= fread($handle, 8080);
                }
                if($content){
                    $code=1;
                }
            }catch (\Exception $e) {
                // 这是进行异常捕获
                $this->app->log->error("解析txt文件异常".json($e->getMessage()));
                return  ['code'=>0,'content'=>"文件解析失败"];
            }

        }else{
            $content="暂不支持该文件";
        }
        $fileType = mb_detect_encoding($content , array('UTF-8','GBK','LATIN1','BIG5')) ;
        if( $fileType != 'UTF-8'){
            $content = mb_convert_encoding($content ,'utf-8' , $fileType);
        }
        return ['code'=>$code,'content'=>$content];
    }
    //提交检测
    public function paperFile($title,$author,$content,$ip){
        //$cof=$this->app->db->name('DigitTestingConfig')->where(['type'=>1,'status'=>1])->find();
        //dump($cof);exit;
        $data = [
            'appid'=>1,
            'title'=>$title,
            'author'=>$author,
            'content'=>$content
        ];
        //腾讯服务器地址
        //$url="http://49.233.250.248:8811/post/";
        //阿里服务器地址
        $url="http://{$ip}:8811/post/";
        $return = $this->send_post($url,$data);
        return json_decode($return,true);
    }
    function curl_get($url){

        $header = array(
            'Accept: application/json',
        );
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);

        // 超时设置，以毫秒为单位
        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);

        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }
    

    function send_post($url, $post_data,$method="POST") {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => $method,
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

    //检测日志
    public function operationLog($uid,$content,$type,$score,$user_name){
        $data=[
            'uid'=>$uid,
            'content'=>$content,
            'type'=>$type,
            'score'=>$score,
            'user_name'=>$user_name,
            'create_time'=>time()
        ];
        $this->app->db->name('digit_operation_log')->save($data);
    }

    //保存检测信息
    public function saveDetectionlist($orderacc,$title="",$author="",$textnumber=0,$taskid="",$iscode,$filepath,$account_id,$integral_cat,$up_ip,$content=null){
        $data=[
            'orderacc'=>$orderacc,
            'title'=>$title,
            'author'=>$author,
            'iscode'=>$iscode,
            'textnumber'=>$textnumber,
            'taskid'=>$taskid,
            'filepath'=>$filepath,
            'account_id'=>$account_id,
            'cat_id'=>$integral_cat,
            'up_ip'=>$up_ip,
            'content'=>$content,
            'date'=>time()
        ];
        return $this->app->db->name('digit_detectionlist')->insertGetId($data);
    }


    //获取检测结果并生成检测报告文档(mht版)
    public function getTestResult($data,$again=false){
        include ("chilkat_9_5_0.php");
        if(!$again){
            if($data['iscode']==4 && $data['zipurl']){
                return $data['zipurl'];
            }
        }
        //原文地址
        $path = $data['filepath'];
        $taskid = $data['taskid'];
        $title = $data['title'];
        $author= $data['author'];
        $orderacc = $data['orderacc'];
        try {
            //生成全文标明引用mht
            $host = "http://".sysconf('site_host');
            $this->app->log->error("生成全文引文标明mht开始");
            $mht = new \CkMht();
            //$html=$this->report($data['id']);
           // $html=iconv("UTF-8","gbk//TRANSLIT",$html);
            $fileName=app()->getRootPath() . "public/storage/report/".time().$data['id']."a.mht"; //保存到文件
           // $success = $mht->HtmlToMHTFile($html,$fileName);
            $success = $mht-> GetAndSaveMHT("{$host}/paper/PaperTest/report?oid=".$data['id'],$fileName);
            if($success !=true){
                $this->app->log->error("生成全文引文标明mht失败");
                $this->app->log->error($mht->lastErrorText());
                return  0;
            }
            $mht1 = new \CkMht();
            //$html1=$this->report1($data['id']);
           // $html1=iconv("UTF-8","gbk//TRANSLIT",$html1);
            $fileName1=app()->getRootPath() . "public/storage/report/".time().$data['id']."b.mht"; //保存到文件
            //$success1 = $mht1->HtmlToMHTFile($html1,$fileName1);
            $success1 = $mht1-> GetAndSaveMHT("{$host}/paper/PaperTest/report1?oid=".$data['id'],$fileName1);
            if($success1 !=true){
                $this->app->log->error("生成全文对照mht失败");
                $this->app->log->error($mht1->lastErrorText());
                return  0;
            }
            //这里需要注意该目录是否存在，并且有创建的权限
            $zipname =app()->getRootPath() . "public/storage/report/{$orderacc}_{$title}_{$author}".$data['id'].".zip";
            $zip = new \ZipArchive();
            $zip->open($zipname, \ZipArchive::CREATE|\ZipArchive::OVERWRITE);
            $zip->addFile($fileName, "{$orderacc}_{$title}_{$author}(全文引文标明).mht");
            $zip->addFile($fileName1, "{$orderacc}_{$title}_{$author}(全文对照).mht");
            //查询代理商的检测报告
            //查询代理商的打包文档并加入压缩包中
            $packfile = $this->app->db->name('digit_packfile')->where(['uid'=>$data['account_id']])->select()->toArray();
            if($packfile){
                foreach ($packfile as $v){
                    $zip->addFile($v['file_url'], $v['file_name']);
                }
            }
            $zip->close();
            unlink($fileName);
            unlink($fileName1);
            $oid = $data['id'];
            unlink(app()->getRootPath() . "public/storage/report/{$oid}c.png");
            unlink(app()->getRootPath() . "public/storage/report/{$oid}r.png");
            $this->app->log->error("检测报告压缩包生成成功");
            return $zipname;
        }catch (\Exception $e) {
            // 这是进行异常捕获
            $this->app->log->error(json($e->getMessage()));
            return  0;
        }
    }
    
    //生成全文标明引用mht
    public function getTestResult1($data){
        include ("chilkat_9_5_0.php");
        //原文地址
        $path = $data['filepath'];
        $taskid = $data['taskid'];
        $title = $data['title'];
        $author= $data['author'];
        $orderacc = $data['orderacc'];
        try {
            $host = "http://".sysconf('site_host');
            $this->app->log->error("生成全文标明引用pdf开始");
            $mht = new \CkMht();
            $fileName=app()->getRootPath() . "public/storage/report/".time()."a.mht"; //保存到文件
           // $success = $mht->HtmlToMHTFile($html,$fileName);
            $success = $mht-> GetAndSaveMHT("{$host}/paper/PaperTest/report?oid=".$data['id'],$fileName);
            if($success !=true){
                $this->app->log->error("生成全文标明引用mht失败");
                $this->app->log->error($mht->lastErrorText());
                return  0;
            }
            $oid = $data['id'];
            unlink(app()->getRootPath() . "public/storage/report/{$oid}c.png");
            unlink(app()->getRootPath() . "public/storage/report/{$oid}r.png");
            return $fileName;
        }catch (\Exception $e) {
            // 这是进行异常捕获
            $this->app->log->error(json($e->getMessage()));
            return  0;
        }
    }
    
     //生成全文对照mht
    public function getTestResult2($data){
        include ("chilkat_9_5_0.php");
        //原文地址
        $path = $data['filepath'];
        $taskid = $data['taskid'];
        $title = $data['title'];
        $author= $data['author'];
        $orderacc = $data['orderacc'];
        try {
            //生成全文对照mht
            $host = "http://".sysconf('site_host');
            $mht = new \CkMht();
            //$html1=$this->report1($data['id']);
           // $html1=iconv("UTF-8","gbk//TRANSLIT",$html1);
            $fileName=app()->getRootPath() . "public/storage/report/".time()."b.mht"; //保存到文件
            //$success1 = $mht1->HtmlToMHTFile($html1,$fileName1);
            $success = $mht-> GetAndSaveMHT("{$host}/paper/PaperTest/report1?oid=".$data['id'],$fileName);
             $this->app->log->error("{$host}/paper/PaperTest/report1?oid=".$data['id']);
            if($success !=true){
                $this->app->log->error("生成全文对照mht失败");
                $this->app->log->error($mht->lastErrorText());
                return  0;
            }
            $oid = $data['id'];
            unlink(app()->getRootPath() . "public/storage/report/{$oid}c.png");
            unlink(app()->getRootPath() . "public/storage/report/{$oid}r.png");
            return $fileName;
        }catch (\Exception $e) {
            // 这是进行异常捕获
            $this->app->log->error(json($e->getMessage()));
            return  0;
        }
    }
    
    //将检测报告打包
    public function getTestResult3($data,$fileName,$fileName1){
        //原文地址
        $path = $data['filepath'];
        $taskid = $data['taskid'];
        $title = $data['title'];
        $author= $data['author'];
        $orderacc = $data['orderacc'];
        try {
            //这里需要注意该目录是否存在，并且有创建的权限
            $zipname =app()->getRootPath() . "public/storage/report/{$orderacc}_{$title}_{$author}".$data['id'].".zip";
            $zip = new \ZipArchive();
            $zip->open($zipname, \ZipArchive::CREATE|\ZipArchive::OVERWRITE);
            $zip->addFile($fileName, "{$orderacc}_{$title}_{$author}(全文引文标明).mht");
            $zip->addFile($fileName1, "{$orderacc}_{$title}_{$author}(全文对照).mht");
            //查询代理商的检测报告
            //查询代理商的打包文档并加入压缩包中
            $packfile = $this->app->db->name('digit_packfile')->where(['uid'=>$data['account_id']])->select()->toArray();
            if($packfile){
                foreach ($packfile as $v){
                    $zip->addFile($v['file_url'], $v['file_name']);
                }
            }
            $zip->close();
            unlink($fileName);
            unlink($fileName1);
            $this->app->log->error("检测报告压缩包生成成功");
            return $zipname;
        }catch (\Exception $e) {
            // 这是进行异常捕获
            $this->app->log->error(json($e->getMessage()));
            return  0;
        }
    }
    


    //获取检测结果并生成检测报告文档(pdf版)
    public function getTestResultpdf($data,$again=false){
        //$delist=$this->app->db->name('digit_detectionlist')->where(['id'=>$data['id']])->find();
        //dump($delist);exit;
        ini_set('pcre.backtrack_limit', 999999999);
        if(!$again){
            if($data['iscode']==4 && $data['zipurl']){
                return $data['zipurl'];
            }
        }
        //原文地址
        $path = $data['filepath'];
        $taskid = $data['taskid'];
        $title = $data['title'];
        $author= $data['author'];
        $orderacc = $data['orderacc'];
        //设置中文编码
        $c=['mode'=>'utf-8','format'=>'A4','useSubstitutions'=>true,'useAdobeCJK'=>true,'autoScriptToLang'=>true,'margin_left'=>3,'margin_right'=>3,'margin_top'=>3,'margin_bottom'=>3,'margin_header'=>0,'margin_footer'=>0, 'orientation'=>'P'];
        $mpdf=new \Mpdf\Mpdf($c);
        $this->app->log->error("生成全文引文标明pdf开始");
        $html=$this->report($data['id']);
        $mpdf->shrink_tables_to_fit = 1;
        $mpdf->WriteHTML($html);
        $fileName=app()->getRootPath() . "public/storage/report/".time().$data['id']."a.pdf"; //保存到文件
        $mpdf->Output($fileName);
        $this->app->log->error("生成全文引文标明pdf结束");
        //生成全文对照pdf
        $this->app->log->error("生成全文对照pdf开始");
        $mpdf1=new \Mpdf\Mpdf($c);
        $html1=$this->report1($data['id']);
        $mpdf1->shrink_tables_to_fit = 1;
        $mpdf1->WriteHTML($html1);
        $fileName1=app()->getRootPath() . "public/storage/report/".time().$data['id']."b.pdf"; //保存到文件
        $mpdf1->Output($fileName1);
        $this->app->log->error("生成全文对照pdf结束");
        $mpdf2=new \Mpdf\Mpdf($c);
        $this->app->log->error("生成简洁pdf开始");
        $html2=$this->reportj($data['id']);
        $mpdf2->shrink_tables_to_fit = 1;
        $mpdf2->WriteHTML($html2);
        $fileName2=app()->getRootPath() . "public/storage/report/".time().$data['id']."j.pdf"; //保存到文件
        $mpdf2->Output($fileName2);
        //这里需要注意该目录是否存在，并且有创建的权限
        $zipname =app()->getRootPath() . "public/storage/report/{$orderacc}_{$title}_{$author}".$data['id'].".zip";
        $zip = new \ZipArchive();
        $zip->open($zipname, \ZipArchive::CREATE|\ZipArchive::OVERWRITE);
        $zip->addFile($fileName2, "{$orderacc}_{$title}_{$author}(简洁).pdf");
        $zip->addFile($fileName, "{$orderacc}_{$title}_{$author}(全文引文标明).pdf");
        $zip->addFile($fileName1, "{$orderacc}_{$title}_{$author}(全文对照).pdf");
        //查询代理商的检测报告
        //查询代理商的打包文档并加入压缩包中
        $packfile = $this->app->db->name('digit_packfile')->where(['uid'=>$data['account_id']])->select()->toArray();
        if($packfile){
            foreach ($packfile as $v){
                $zip->addFile($v['file_url'], $v['file_name']);
            }
        }
        $zip->close();
        unlink($fileName);
        unlink($fileName1);
        unlink($fileName2);
        $oid = $data['id'];
        unlink(app()->getRootPath() . "public/storage/report/{$oid}c.png");
        unlink(app()->getRootPath() . "public/storage/report/{$oid}r.png");

        $this->app->log->error("检测报告压缩包生成成功");
        $l=app()->getRootPath()."storage/report/{$orderacc}_{$title}_{$author}.zip";
        return $zipname;
//        $html=$this->report($data['id']);
//        dump($html);exit;
        //生成全文标明引用pdf
        try {
            //设置中文编码
            $mpdf=new \Mpdf\Mpdf(['mode'=>'utf-8','format'=>'A4','useSubstitutions'=>true,'useAdobeCJK'=>true,'autoScriptToLang'=>true,'autoLangToFont'=>true,'mgl'=>15,'mgr'=>15,'mgt'=>16,'mgb'=>16,'mgh'=>9,'mgf'=>9, 'orientation'=>'P']);
            $this->app->log->error("生成全文标明引用pdf开始");
            // $paperTest = new PaperTest();

            $html=$this->report($data['id']);
            //$url=sysconf('site_host')."/paper/PaperTest/report?oid=".$data['id'];
            // $html=file_get_contents($url);
            $mpdf->shrink_tables_to_fit = 1;
            $mpdf->WriteHTML($html);
            $fileName=app()->getRootPath() . "public/storage/report/".time()."a.pdf"; //保存到文件
            $mpdf->Output($fileName);
            $this->app->log->error("生成全文标明引用pdf结束");
            //生成全文对照pdf
            $this->app->log->error("生成全文对照pdf开始");
            $mpdf1=new \Mpdf\Mpdf(['mode'=>'utf-8','format'=>'A4','useSubstitutions'=>true,'useAdobeCJK'=>true,'autoScriptToLang'=>true,'autoLangToFont'=>true,'mgl'=>15,'mgr'=>15,'mgt'=>16,'mgb'=>16,'mgh'=>9,'mgf'=>9, 'orientation'=>'P']);
            // $url1=sysconf('site_host')."/paper/PaperTest/report1?oid=".$data['id'];
            // $html1=file_get_contents($url1);
            $html1=$this->report1($data['id']);
            $mpdf1->shrink_tables_to_fit = 1;
            $mpdf1->WriteHTML($html1);
            $fileName1=app()->getRootPath() . "public/storage/report/".time()."b.pdf"; //保存到文件
            $mpdf1->Output($fileName1);
            $this->app->log->error("生成全文对照pdf结束");
            //这里需要注意该目录是否存在，并且有创建的权限
            $zipname =app()->getRootPath() . "public/storage/report/{$orderacc}_{$title}_{$author}.zip";
            $zip = new \ZipArchive();
            $zip->open($zipname, \ZipArchive::CREATE|\ZipArchive::OVERWRITE);
            $zip->addFile($fileName, "{$orderacc}_{$title}_{$author}(全文标明引用).pdf");
            $zip->addFile($fileName1, "{$orderacc}_{$title}_{$author}(全文对照引用).pdf");
            //查询代理商的检测报告
            //查询代理商的打包文档并加入压缩包中
            $packfile = $this->app->db->name('digit_packfile')->where(['uid'=>$data['account_id']])->select()->toArray();
            if($packfile){
                foreach ($packfile as $v){
                    $zip->addFile($v['file_url'], $v['file_name']);
                }
            }
            $zip->close();
            unlink($fileName);
            unlink($fileName1);
            $oid = $data['id'];
            unlink(app()->getRootPath() . "public/storage/report/{$oid}c.png");
            unlink(app()->getRootPath() . "public/storage/report/{$oid}r.png");

            $this->app->log->error("检测报告压缩包生成成功");
            $l=app()->getRootPath()."storage/report/{$orderacc}_{$title}_{$author}.zip";
            return $zipname;
        }catch (\Exception $e) {
            // 这是进行异常捕获
            $this->app->log->error(json($e->getMessage()));
            return  0;
        }
    }
    /*
     * 读取docx文件内容
     * $source 文件路径
     */
    public function readWordToHtml($source)
    {
        $phpWord = \PhpOffice\PhpWord\IOFactory::load($source);
        $html = '';
        foreach ($phpWord->getSections() as $section) {
            foreach ($section->getElements() as $ele1) {
               // dump($ele1);
//                if(method_exists($ele1,'getParagraphStyle')){
//                    $paragraphStyle = $ele1->getParagraphStyle();
//                    if ($paragraphStyle) {
//                        $html .=  $paragraphStyle->getAlignment();
//                    }
//                }

                if ($ele1 instanceof \PhpOffice\PhpWord\Element\TextRun) {
                    foreach ($ele1->getElements() as $ele2) {
                        if ($ele2 instanceof \PhpOffice\PhpWord\Element\Text) {
//                            $style = $ele2->getFontStyle();
//                            $fontFamily = mb_convert_encoding($style->getName(), 'GBK', 'UTF-8');
//                            $fontSize = $style->getSize();
//                            $isBold = $style->isBold();
//                            $styleString = '';
//                            $fontFamily && $styleString .= "font-family:{$fontFamily};";
//                            $fontSize && $styleString .= "font-size:{$fontSize}px;";
//                            $isBold && $styleString .= "font-weight:bold;";
                            $html.=mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8')."\n";
                            //$html .= sprintf('%s', $styleString, mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8'));
                        }
//                        elseif ($ele2 instanceof \PhpOffice\PhpWord\Element\Image) {
//                            $imageSrc = 'images/' . md5($ele2->getSource()) . '.' . $ele2->getImageExtension();
//                            $imageData = $ele2->getImageStringData(true);
//                            // $imageData = 'data:' . $ele2->getImageType() . ';base64,' . $imageData;
//                            file_put_contents($imageSrc, base64_decode($imageData));
//                            $html .= '<img src="'. $imageSrc .'" style="width:100%;height:auto">';
//                        }
                    }
                }
                //$html .= '</p>';
            }
        }

        return mb_convert_encoding($html, 'UTF-8', 'GBK');
    }

    //查询检测结果
    public function checkResult($taskid){
        $d=[
            'appid'=>1,
            'taskid'=>$taskid
        ];
        $url="http://49.233.250.248:8811/query/";
        $info = PaperTestService::instance()->send_post($url,$d);
        if($info){
            $info = json_decode($info,true);
            if($info['result']==1){
                return $info;
            }
        }
        return 0;
    }

    //全文对照
    public function report1($oid){
        $oid = input('oid')?input('oid'):$oid;
        $delist=$this->app->db->name('digit_detectionlist')->where(['id'=>$oid])->find();
        $data=json_decode($delist['check_result'],true);
        View::assign('data',$data);
        //生成距形图
        $rectangle = $this->rectangleImg($data['checkResult']['report_annotation_ref']['similar_offsets'],$data['checkResult']['word_count'],$oid);
        View::assign('rectangle',$rectangle);
        //生成饼图
        $cake = $this->cakeImg($data['checkResult']['similarity'],$oid);
        View::assign('cake',$cake);
        return View::fetch("paper@paper_test/pA1");
    }

    //简洁报告
    public function reportj($oid){
        $oid = input('oid')?input('oid'):$oid;
        $delist=$this->app->db->name('digit_detectionlist')->where(['id'=>$oid])->find();
        $data=json_decode($delist['check_result'],true);
        View::assign('data',$data);
        //生成距形图
        $rectangle = $this->rectangleImg($data['checkResult']['report_annotation_ref']['similar_offsets'],$data['checkResult']['word_count'],$oid);
        View::assign('rectangle',$rectangle);
        //生成饼图
        $cake = $this->cakeImg($data['checkResult']['similarity'],$oid);
        View::assign('cake',$cake);
        return View::fetch("paper@paper_test/pjA");
    }
    //全文引文标明
    public function report($oid){
        $oid = input('oid')?input('oid'):$oid;
        $delist=$this->app->db->name('digit_detectionlist')->where(['id'=>$oid])->find();
        $data=json_decode($delist['check_result'],true);
        View::assign('data',json_decode($delist['check_result'],true));
        $similar_offsets= $data['checkResult']['report_annotation_ref']['chapters'];
        foreach ($similar_offsets as $k=>$v){
            preg_match_all ("/<em class='similar'>(.*)<\/em>/U", $v['text'], $pat_array);
            $similar_offsets[$k]['test_arr']=$pat_array[1];
        }


        //生成距形图
        $rectangle = $this->rectangleImg($data['checkResult']['report_annotation_ref']['similar_offsets'],$data['checkResult']['word_count'],$oid);
        View::assign('rectangle',$rectangle);
        //dump($similar_offsets);exit;
        //生成饼图
        $cake = $this->cakeImg($data['checkResult']['similarity'],$oid);
        View::assign('cake',$cake);
        View::assign('similar_offsets',$similar_offsets);
        return View::fetch("paper@paper_test/pA");
    }

    //生成饼图
    public function cakeImg($similarity,$oid){
        //分析思路（先画出扇形）
        //1.画布
        $im=imagecreatetruecolor(100,100);

        //默认是黑色背景，修改为白色
        $white=imagecolorallocate($im,247,247,247);
        imagefill($im,0,0,$white);
        $d = 360*$similarity;
        $red=imagecolorallocate($im,224,107,125);
        //无问题部分颜色
        $blue=imagecolorallocate($im,134,134,134);
        imagefilledarc($im,50,50,100,100,$d,360,$blue,IMG_ARC_PIE);
        imagefilledarc($im,50,50,100,100,0,$d,$red,IMG_ARC_PIE);
        //输出图像到网页，也可以另存
       // header("content-type:image/png");
        $filename=app()->getRootPath() . "public/storage/report/{$oid}c.png";
        imagepng($im,$filename);
        imagedestroy($im);
        //shell_exec("chmod 777 {$filename}");
        return "http://".sysconf('site_host')."/storage/report/{$oid}c.png";

    }

    //生成矩形图
    public function rectangleImg($similar_offsets,$word_count,$oid){

        //分析思路（先画出扇形）
        //1.画布
        $im=imagecreatetruecolor(604,15);

        //默认是黑色背景，修改为白色
        $white=imagecolorallocate($im,134,134,134);
        imagefill($im,0,0,$white);
        $red=imagecolorallocate($im,224,107,125);
        $num = 800/$word_count;
        foreach ($similar_offsets as $k=>$v){
            $star = $v['start']*$num;
            $w = $v['end']*$num;

            imagefilledrectangle($im,$star,0,$w,15,$red);
        }

        //imagefilledrectangle($im,0,0,10,15,$red);
        //imagefilledrectangle($im,100,0,600,15,$red);
        //header("content-type:image/png");

        $filename=app()->getRootPath() . "public/storage/report/{$oid}r.png";

        imagepng($im,$filename);
        imagedestroy($im);
       // shell_exec("chmod 777 {$filename}");
        return "http://".sysconf('site_host').  "/storage/report/{$oid}r.png";
    }


    //自动发货
    public function LogisticsDummySend($tids,$uid){

        $appKey = "12345";
        $accessToken=$this->app->db->name('system_user')->where(['id'=>$uid])->value('token');
        $appSecret = sysconf('wechat.appsecret');
        //业务参数
        $params = array();
        $params['tids'] = $tids;
        $params['timestamp'] = time();
        $params['sign'] = $this->sign($params,$appSecret);

        //设置Header
        $headers[] = "Authorization: Bearer ".$accessToken;
        $headers[] = "ApiVersion: 1";

        $ci = curl_init();
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ci, CURLOPT_ENCODING, "");
        if (version_compare(phpversion(), '5.4.0', '<')) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, 1);
        } else {
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, 2);
        }
        curl_setopt($ci, CURLOPT_HEADER, FALSE);
        curl_setopt($ci, CURLOPT_POST, TRUE);
        curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ci, CURLOPT_URL, 'http://gw.api.agiso.com/alds/Trade/LogisticsDummySend' );
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers );
        curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE );
        $response = curl_exec($ci);
        curl_close ($ci);
        $response1 = json_decode($response,true);
        if(!$response1['IsSuccess']){
            $this->app->log->error("订单{$tids}自动发货失败：");
            $this->app->log->error($response);
        }
        return $response;
    }
    public function sign($args,$client_secret)
    {
        ksort($args);
        $str='';
        foreach ($args as $key => $value)
        {
            $str .= ($key . $value);
        }
        //头尾加入AppSecret
        $str = $client_secret . $str . $client_secret;
        $encodeStr = md5($str);
        return $encodeStr;
    }
    
    public function r($source){
        $phpWord = \PhpOffice\PhpWord\IOFactory::load($source);
        $htmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, "HTML");
        $content = '';
        foreach ($phpWord->getSections() as $section) {
            $writer = new \PhpOffice\PhpWord\Writer\HTML\Element\Container($htmlWriter, $section);
            $content .= $writer->write();
        }
        return $content;
    }
    
    //查询检测结果1
    public function checkResult1($taskid,$id,$ip){
        try {
            $d=[
                'appid'=>1,
                'taskid'=>$taskid
            ];
            //腾讯服务器地址
            //$url="http://49.233.250.248:8811/query/";
            //阿里服务器地址
            $url="http://{$ip}:8811/query/";
            $info1 = PaperTestService::instance()->send_post($url,$d);
            // $this->app->log->error($info);
            if(empty($info1)){
                return 0;
            }else{
                $info = json_decode($info1,true);
                if($info['result']=!1||$info['table']['state']!=2){
                    if(isset($info['table']['state'])){
                       $updata['iscode']=$info['table']['state'];
                       $this->app->db->name("digit_detectionlist")->where(['id'=>$id])->update($updata);
                    }
                   return 0;
                }else{
                    $updata['iscode']=3;
                    $updata['similarity']=$info['table']['similarity'];
                    $updata['check_result']=$info1;
                    $this->app->db->name("digit_detectionlist")->where(['id'=>$id])->update($updata);
                    //生成检测报告并打包
                    return 1;
                }
            }
        }catch (\Exception $e) {
            // 这是进行异常捕获
            //$this->app->log->error(json($e->getMessage()));
            return  0;
        }
    }

}